package com.anti.modular.owner.ownerleasebill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.core.utils.DecimalUtils;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.core.utils.IdFlowingUtil;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.billwater.entity.BillWater;
import com.anti.modular.bus.billwater.entity.BillWaterRoom;
import com.anti.modular.bus.billwater.service.BillWaterService;
import com.anti.modular.bus.billwaterdetail.entity.BillWaterDetail;
import com.anti.modular.bus.billwaterdetail.service.BillWaterDetailService;
import com.anti.modular.bus.busbasicsettings.entity.BusBasicSettings;
import com.anti.modular.bus.busbasicsettings.service.BusBasicSettingsService;
import com.anti.modular.bus.busmeansoftransaction.entity.BusMeansOfTransaction;
import com.anti.modular.bus.busmeansoftransaction.service.BusMeansOfTransactionService;
import com.anti.modular.bus.busroom.service.BusRoomService;
import com.anti.modular.bus.houselease.vo.DayCompare;
import com.anti.modular.bus.houselease.vo.TimeVo;
import com.anti.modular.commonutils.CalculateQs;
import com.anti.modular.owner.ownerlease.entity.OwnerLease;
import com.anti.modular.owner.ownerlease.service.OwnerLeaseService;
import com.anti.modular.owner.ownerleasebill.entity.OwnerLeaseBill;
import com.anti.modular.owner.ownerleasebill.enums.OwnerLeaseBillExceptionEnum;
import com.anti.modular.owner.ownerleasebill.param.OwnerLeaseBillEditParam;
import com.anti.modular.owner.ownerleasebill.param.OwnerLeaseBillParam;
import com.anti.modular.owner.ownerleasebill.result.*;
import com.anti.modular.owner.ownerleasebill.service.OwnerLeaseBillService;
import com.anti.modular.owner.ownerleasebilladjust.entity.OwnerLeaseBillAdjust;
import com.anti.modular.owner.ownerleasebilladjust.service.OwnerLeaseBillAdjustService;
import com.anti.modular.owner.ownerleasebilldetail.entity.OwnerLeaseBillDetail;
import com.anti.modular.owner.ownerleasebilldetail.service.OwnerLeaseBillDetailService;
import com.anti.modular.owner.ownerleasefees.entity.OwnerLeaseFees;
import com.anti.modular.owner.ownerleasefees.service.OwnerLeaseFeesService;
import com.anti.modular.owner.ownerleaseroom.entity.OwnerLeaseRoom;
import com.anti.modular.owner.ownerleaseroom.service.OwnerLeaseRoomService;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import org.omg.CORBA.portable.ValueOutputStream;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 業主賬單service接口实现类
 *
 * @author anti
 * @date 2021-05-20 14:25:38
 */
@Service
public class OwnerLeaseBillServiceImpl implements OwnerLeaseBillService {
    @Resource
    DBUtils dbUtils;
    @Resource
    OwnerLeaseService ownerLeaseService;
    @Resource
    BusBasicSettingsService busBasicSettingsService;
    @Resource
    OwnerLeaseBillDetailService ownerLeaseBillDetailService;
    @Resource
    OwnerLeaseRoomService ownerLeaseRoomService;
    @Resource
    BusMeansOfTransactionService busMeansOfTransactionService;
    @Resource
    OwnerLeaseFeesService ownerLeaseFeesService;
    @Resource
    BillWaterService billWaterService;
    @Resource
    BillWaterDetailService billWaterDetailService;
    @Resource
    BusRoomService busRoomService;
    @Resource
    OwnerLeaseBillAdjustService ownerLeaseBillAdjustService;
    @Override
    public OwnerLeaseBill getById(OwnerLeaseBillParam ownerLeaseBillParam){
        String sql="select * from owner_lease_bill where id =? ";
        return dbUtils.get(sql,OwnerLeaseBill.class,ownerLeaseBillParam.getId());
    }

    @Override
    public OwnerLeaseBill getNowYxById(Long leaseId) {
        String sql="select * from owner_lease_bill where owner_lease_id =? and status=0 and bill_status=1";
        return dbUtils.getFirst(sql,OwnerLeaseBill.class,leaseId);
    }

    @Override
    public OwnerLeaseNumResult getOwnerBillNum() {
        String sql="SELECT (select count(*) from owner_lease_bill where bill_status=1 and status=0) as all_num," +
                "(select count(*) from owner_lease_bill where bill_status=1 and status=0 and DATE_FORMAT(rented_day,'%Y-%m-%d')<DATE_FORMAT(NOW(),'%Y-%m-%d')) as yq_num," +
                "(select count(*) from owner_lease_bill where bill_status=1 and status=0 and DATE_FORMAT(rented_day,'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d')) as now_num," +
                "(select count(*) from owner_lease_bill where bill_status=3 and status=0) as qs_num from DUAL";
        return dbUtils.getFirst(sql,OwnerLeaseNumResult.class);
    }

    @Override
    public PageResult page(PageParam pageParam,OwnerLeaseBillParam ownerLeaseBillParam) {
        StringBuilder sb=new StringBuilder("select a.*,b.room_name,b.name,b.phone from owner_lease_bill a right JOIN owner_lease b on b.id=a.owner_lease_id where 1=1 and a.status = 0 and a.bill_status<>5");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(ownerLeaseBillParam)) {
            // 根据租金 查询
            if (ObjectUtil.isNotEmpty(ownerLeaseBillParam.getType())) {
                int type = ownerLeaseBillParam.getType();
                if (type==1){
                    sb.append(" and  a.bill_status in (1,3)");
                    if (ObjectUtil.isNotEmpty(ownerLeaseBillParam.getNumType())) {
                        int numType = ownerLeaseBillParam.getNumType();
                        if (numType==1){
                            sb.append(" and DATE_FORMAT(a.rented_day,'%Y-%m-%d')<DATE_FORMAT(NOW(),'%Y-%m-%d')");
                        }else if (numType==2){
                            sb.append(" and DATE_FORMAT(a.rented_day,'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d')");
                        }else if (numType==3){
                            sb.append(" and  a.bill_status =3 ");
                        }
                    }
                }else {
                    sb.append(" and  a.bill_status in (2,4)");
                    boolean searchNowType = ownerLeaseBillParam.isSearchNowType();
                    if (searchNowType){
                        sb.append(" and  b.lease_status in (1,3)");
                    }
                }
            }
            // 根据業主名稱 查询
            if (ObjectUtil.isNotEmpty(ownerLeaseBillParam.getSearchType())&&ObjectUtil.isNotEmpty(ownerLeaseBillParam.getSearchValue())) {
                String searchType = ownerLeaseBillParam.getSearchType();
                if ("1".equals(searchType)){
                    sb.append(" and b.id in ( select owner_lease_id from  owner_lease_room where room_id in ( select id from bus_room where estateid in (select id from bus_real_estate where status =0 and name like ? )))");
                    param.add(ownerLeaseBillParam.getSearchValue()+"%");
                }else if ("2".equals(searchType)){
                    sb.append(" and b.id in (select owner_lease_id from  owner_lease_room where room_id in ( select id from bus_room where code  like ? ))");
                    param.add(ownerLeaseBillParam.getSearchValue()+"%");
                }else if ("3".equals(searchType)){
                    sb.append(" and b.name  like ? ");
                    param.add("%"+ownerLeaseBillParam.getSearchValue()+"%");
                }else if ("4".equals(searchType)){
                    sb.append(" and b.phone  like ? ");
                    param.add(ownerLeaseBillParam.getSearchValue()+"%");
                }
            }
        }
        sb.append(" order by a.create_time desc");
        PageResult pageResult = dbUtils.query(pageParam, sb.toString(), OwnerLeaseBillResult.class, param.toArray());
        List<OwnerLeaseBillResult> houseBillResults = (List<OwnerLeaseBillResult>) pageResult.getData();
        List<Long> collectIds = houseBillResults.stream().map(x -> x.getId()).collect(Collectors.toList());
        String sql ="select * from owner_lease_bill_detail where owner_bill_id in (:ids) and status = 0";
        HashMap<Object, Object> paramChre = CollectionUtil.newHashMap();
        paramChre.put("ids",collectIds);
        List<OwnerLeaseBillDetail> houseBillDetails=new ArrayList<>();
        if (collectIds.size()>0){
            houseBillDetails  = dbUtils.query(sql, OwnerLeaseBillDetail.class, paramChre);
        }
        for (int i = 0; i < houseBillResults.size(); i++) {
            OwnerLeaseBillResult houseBillResult = houseBillResults.get(i);
            List<OwnerLeaseBillDetail> collect = houseBillDetails.stream().filter(a -> a.getOwnerBillId().equals(houseBillResult.getId())).collect(Collectors.toList());
            BigDecimal total=new BigDecimal(0.00);
            for (int i1 = 0; i1 < collect.size(); i1++) {
                OwnerLeaseBillDetail ownerLeaseBillDetail = collect.get(i1);
                if (ownerLeaseBillDetail.getBillInOutType().intValue()==2){
                    ownerLeaseBillDetail.setAmount(ownerLeaseBillDetail.getAmount().negate());
                    total=DecimalUtils.add(total,ownerLeaseBillDetail.getAmount());
                }else {
                    ownerLeaseBillDetail.setAmount(ownerLeaseBillDetail.getAmount());
                    total=DecimalUtils.add(total,ownerLeaseBillDetail.getAmount());
                }
            }
            houseBillResult.setSubtotal(DecimalUtils.toPlainString(total));
            houseBillResult.setDetails(collect);
        }
        pageResult.setData(houseBillResults);
        return pageResult;
    }

    @Override
    public PageResult ownerLeaseBillPageByLeaseId(PageParam pageParam, OwnerLeaseBillParam ownerLeaseBillParam) {
        StringBuilder sb=new StringBuilder("select a.* from owner_lease_bill a where 1=1 and a.status = 0 and a.bill_status <> 5 and a.owner_lease_id =? order by qs_num desc");
        PageResult query = dbUtils.query(pageParam, sb.toString(), OwnerLeaseBillResult.class, ownerLeaseBillParam.getOwnerLeaseId());
        List<OwnerLeaseBillResult> houseBillResults = (List<OwnerLeaseBillResult>) query.getData();
        List<Long> collectIds = houseBillResults.stream().map(x -> x.getId()).collect(Collectors.toList());
        String sql ="select * from owner_lease_bill_detail where owner_bill_id in (:ids) and status = 0";
        HashMap<Object, Object> param = CollectionUtil.newHashMap();
        param.put("ids",collectIds);
        List<OwnerLeaseBillDetail> houseBillDetails =new ArrayList<>();
        if (collectIds.size()>0){
            houseBillDetails = dbUtils.query(sql, OwnerLeaseBillDetail.class, param);
        }
        for (int i = 0; i < houseBillResults.size(); i++) {
            OwnerLeaseBillResult houseBillResult = houseBillResults.get(i);
            List<OwnerLeaseBillDetail> collect = houseBillDetails.stream().filter(a -> a.getOwnerBillId().equals(houseBillResult.getId())).collect(Collectors.toList());
            BigDecimal total=new BigDecimal(0.00);
            for (int i1 = 0; i1 < collect.size(); i1++) {
                OwnerLeaseBillDetail ownerLeaseBillDetail = collect.get(i1);
                if (ownerLeaseBillDetail.getBillInOutType().intValue()==2){
                    ownerLeaseBillDetail.setAmount(ownerLeaseBillDetail.getAmount().negate());
                    total=DecimalUtils.add(total,ownerLeaseBillDetail.getAmount());
                }else {
                    ownerLeaseBillDetail.setAmount(ownerLeaseBillDetail.getAmount());
                    total=DecimalUtils.add(total,ownerLeaseBillDetail.getAmount());
                }
            }
            houseBillResult.setSubtotal(DecimalUtils.toPlainString(total));
            houseBillResult.setDetails(collect);
        }
        query.setData(houseBillResults);
        return query;
    }

    @Override
    public List<OwnerLeaseBill> list(OwnerLeaseBillParam ownerLeaseBillParam) {
        String sql="";
        return dbUtils.query(sql,OwnerLeaseBill.class);
    }

    @Override
    public void add(OwnerLeaseBillParam ownerLeaseBillParam) {
        OwnerLeaseBill ownerLeaseBill = new OwnerLeaseBill();
        BeanUtil.copyProperties(ownerLeaseBillParam, ownerLeaseBill);
        dbUtils.insert(ownerLeaseBill);
    }

    @Override
    public void addBillListByLease(OwnerLease ownerLease,List<OwnerLeaseFees> ownerLeaseFees) {
        Long ownerLeaseId = ownerLease.getId();
        Date rentStartDate = ownerLease.getRentStartDate();
        Date rentEndDate = ownerLease.getRentEndDate();
        Integer receiptFu = ownerLease.getReceiptFu();
        Integer receiptYj = ownerLease.getReceiptYj();
        Integer billEndTqData = ownerLease.getBillEndTqData();
        BigDecimal rent = ownerLease.getRent();
        BigDecimal deposit = ownerLease.getDeposit();
        //基础设置
        BusBasicSettings one = busBasicSettingsService.getOne();
        //计算费用时月天数 （字典 0按固定30天算 1按月份实际天数
        int calculateStyle = one.getCalculateStyle();
        //账单金额取整 （字典 0关闭 1打开 小数点后四舍五入）
        int amount = one.getAmount();

        Date date = new Date();
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        List<TimeVo> timeVos = CalculateQs.calculateQs(rentStartDate, rentEndDate, receiptFu, receiptYj);

        List<OwnerLeaseBill> ownerLeaseBills = new ArrayList<>();
        OwnerLeaseBill ownerLeasePre=null;
        for (TimeVo timeVo : timeVos) {
            ownerLeasePre=new OwnerLeaseBill();
            ownerLeasePre.setRentStartDate(timeVo.getStart());
            ownerLeasePre.setRentEndDate(timeVo.getEnd());
            ownerLeaseBills.add(ownerLeasePre);
        }
        for (int i = 0; i < ownerLeaseBills.size(); i++) {
            OwnerLeaseBill ownerLeaseBill = ownerLeaseBills.get(i);
            Date rentStartDate1 = ownerLeaseBill.getRentStartDate();
            Date rentEndDate1 = ownerLeaseBill.getRentEndDate();
            ownerLeaseBill.setOwnerLeaseId(ownerLeaseId);
            String snowflakesId = IdFlowingUtil.getSnowflakesId("YZZD");
            ownerLeaseBill.setNo(snowflakesId);
            int qs=i+1;
            ownerLeaseBill.setQsNum(qs);
            if (qs == 1) {
                ownerLeaseBill.setBillStatus(1);
            }else {
                ownerLeaseBill.setBillStatus(5);
            }
            ownerLeaseBill.setRentFree(0);
            ownerLeaseBill.setRentAdjust(0);
            Date rentedDay = CalculateQs.createRentedDay(billEndTqData, ownerLeaseBill.getRentStartDate());
            ownerLeaseBill.setRentedDay(rentedDay);
            ownerLeaseBill.setRent(rent);
            ownerLeaseBill.setStatus(0);
            if (qs == 1) {
                ownerLeaseBill.setCreateTime(date);
                ownerLeaseBill.setCreateUser(sysLoginUserId);
            }
            String key = dbUtils.insertKey(ownerLeaseBill).toString();
            long pkBillId = Long.parseLong(key);
            ownerLeaseBill.setId(pkBillId);
            if (qs == 1) {
                //第一期創建明細
                //新增固定費用
                ownerLeaseBillDetailService.addGdfy(ownerLeaseFees,pkBillId);
                //新增押金
                ownerLeaseBillDetailService.addYj(deposit,pkBillId,1);
                //新增租金
                BigDecimal rentMoney = CalculateQs.getRentMoney(amount, calculateStyle, receiptFu, receiptYj, rentStartDate1, rentEndDate1, rent);
                ownerLeaseBillDetailService.addZj(rentMoney,pkBillId);
            }
        }
    }

    @Override
    public void addXuZuBillListByLease(int maxQs, OwnerLease ownerLease, Date start,Date end) {
        Integer receiptFu = ownerLease.getReceiptFu();
        Integer receiptYj = ownerLease.getReceiptYj();
        Long ownerLeaseId = ownerLease.getId();
        BigDecimal rent = ownerLease.getRent();
        Integer billEndTqData = ownerLease.getBillEndTqData();
        List<TimeVo> timeVos = CalculateQs.calculateQs(start, end, receiptFu, receiptYj);
        List<OwnerLeaseBill> ownerLeaseBills = new ArrayList<>();
        OwnerLeaseBill ownerLeasePre=null;
        for (TimeVo timeVo : timeVos) {
            ownerLeasePre=new OwnerLeaseBill();
            ownerLeasePre.setRentStartDate(timeVo.getStart());
            ownerLeasePre.setRentEndDate(timeVo.getEnd());
            ownerLeaseBills.add(ownerLeasePre);
        }
        for (int i = 0; i < ownerLeaseBills.size(); i++) {
            OwnerLeaseBill ownerLeaseBill = ownerLeaseBills.get(i);
            ownerLeaseBill.setOwnerLeaseId(ownerLeaseId);
            String snowflakesId = IdFlowingUtil.getSnowflakesId("YZZD");
            ownerLeaseBill.setNo(snowflakesId);
            int qs=maxQs+i+1;
            ownerLeaseBill.setQsNum(qs);
            ownerLeaseBill.setBillStatus(5);
            ownerLeaseBill.setRentFree(0);
            ownerLeaseBill.setRentAdjust(0);
            Date rentedDay = CalculateQs.createRentedDay(billEndTqData, ownerLeaseBill.getRentStartDate());
            ownerLeaseBill.setRentedDay(rentedDay);
            ownerLeaseBill.setRent(rent);
            ownerLeaseBill.setStatus(0);
            dbUtils.insert(ownerLeaseBill);
        }
    }


    @Override
    public void addNewBillPlanByLease(int maxQs, OwnerLease ownerLease, OwnerLeaseBill nowLease,List<OwnerLeaseFees> ownerLeaseFees) {
        Date rentStartDate = nowLease.getRentStartDate();
        Date rentEndDate = ownerLease.getRentEndDate();
        Integer receiptFu = ownerLease.getReceiptFu();
        Integer receiptYj = ownerLease.getReceiptYj();
        Long ownerLeaseId = ownerLease.getId();
        BigDecimal rent = ownerLease.getRent();
        Integer billEndTqData = ownerLease.getBillEndTqData();
        //删除账单及调整记录
        deleteNowBillAndNowBillDetaillAndSufBill(ownerLeaseId,nowLease.getId());
        List<TimeVo> timeVos = CalculateQs.calculateQs(rentStartDate, rentEndDate, receiptFu, receiptYj);
        List<OwnerLeaseBill> ownerLeaseBills = new ArrayList<>();
        OwnerLeaseBill ownerLeasePre=null;
        for (TimeVo timeVo : timeVos) {
            ownerLeasePre=new OwnerLeaseBill();
            ownerLeasePre.setRentStartDate(timeVo.getStart());
            ownerLeasePre.setRentEndDate(timeVo.getEnd());
            ownerLeaseBills.add(ownerLeasePre);
        }
        for (int i = 0; i < ownerLeaseBills.size(); i++) {
            OwnerLeaseBill ownerLeaseBill = ownerLeaseBills.get(i);
            ownerLeaseBill.setOwnerLeaseId(ownerLeaseId);
            String snowflakesId = IdFlowingUtil.getSnowflakesId("YZZD");
            ownerLeaseBill.setNo(snowflakesId);
            int qs=maxQs+i;
            ownerLeaseBill.setQsNum(qs);
            ownerLeaseBill.setBillStatus(5);
            ownerLeaseBill.setRentFree(0);
            ownerLeaseBill.setRentAdjust(0);
            Date rentedDay = CalculateQs.createRentedDay(billEndTqData, ownerLeaseBill.getRentStartDate());
            ownerLeaseBill.setRentedDay(rentedDay);
            ownerLeaseBill.setRent(rent);
            ownerLeaseBill.setStatus(0);
            if (qs ==maxQs){
                ownerLeaseBill.setBillStatus(1);
                String insertKey = dbUtils.insertKey(ownerLeaseBill).toString();
                long pkBill = Long.parseLong(insertKey);
                ownerLeaseBillDetailService.addGdfy(ownerLeaseFees,pkBill);
            }else {
                dbUtils.insert(ownerLeaseBill);
            }
        }
    }

    public void deleteNowBillAndNowBillDetaillAndSufBill(Long leaseId,Long nowBillId){
        //刪除賬單詳情
       ownerLeaseBillDetailService.deleteByOwnerBillId(nowBillId);
       String updateNowSufSql="update owner_lease_bill set status=2,update_time=?,update_user=? where id >=? and owner_lease_id=?";
       dbUtils.execSql(updateNowSufSql,new Date(),LoginContextHolder.me().getSysLoginUserId(),nowBillId,leaseId);
       ownerLeaseBillAdjustService.deleteSuf(leaseId,nowBillId);
    }

    @Override
    public void addQsBillListByLease(OwnerLease ownerLease,int maxQs) {
        Long ownerLeaseId = ownerLease.getId();
        BigDecimal rent = ownerLease.getRent();
        OwnerLeaseBill ownerLeaseBill =new OwnerLeaseBill();
        ownerLeaseBill.setOwnerLeaseId(ownerLeaseId);
        String snowflakesId = IdFlowingUtil.getSnowflakesId("YZZD");
        ownerLeaseBill.setNo(snowflakesId);
        int qs=maxQs+99;
        ownerLeaseBill.setQsNum(qs);
        ownerLeaseBill.setBillStatus(3);
        ownerLeaseBill.setRentFree(0);
        ownerLeaseBill.setRentAdjust(0);
        Date rentedDay = ownerLease.getRetrieveDate();
        ownerLeaseBill.setRentedDay(rentedDay);
        ownerLeaseBill.setRent(rent);
        ownerLeaseBill.setStatus(0);
        String key = dbUtils.insertKey(ownerLeaseBill).toString();
        long pkId = Long.parseLong(key);
        //新增押金
        BigDecimal deposit = ownerLease.getDeposit();
        ownerLeaseBillDetailService.addYj(deposit,pkId,2);
        //新增固定費用
        List<OwnerLeaseFees> ownerLeaseFees = ownerLeaseFeesService.getGdfyByLeaseId(ownerLeaseId);
        ownerLeaseBillDetailService.addGdfy(ownerLeaseFees,pkId);
    }

    public void delete(OwnerLeaseBillParam ownerLeaseBillParam) {
        String sql="delete  from owner_lease_bill where id =? ";
        dbUtils.execSql(sql,ownerLeaseBillParam.getId());
    }

    public void edit(OwnerLeaseBillEditParam ownerLeaseBillParam) {
        String sql="select * from owner_lease_bill where id =? ";
        OwnerLeaseBill ownerLeaseBill = dbUtils.get(sql, OwnerLeaseBill.class, ownerLeaseBillParam.getId());
        OwnerLeaseBillParam ownerLeaaram=new OwnerLeaseBillParam();
        ownerLeaaram.setId(ownerLeaseBill.getId());
        ownerLeaaram.setOwnerLeaseId(ownerLeaseBill.getOwnerLeaseId());
        check(ownerLeaaram);
        ownerLeaseBill.setRemark(ownerLeaseBillParam.getRemark());
        ownerLeaseBill.setUpdateTime(new Date());
        ownerLeaseBill.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(ownerLeaseBill);
        Long id = ownerLeaseBill.getId();
        int type = ownerLeaseBillParam.getType();
        if (type ==2) {
            //清算賬單修改
            List<OwnerLeaseBillDetail> yjList = ownerLeaseBillParam.getYjList();
            ownerLeaseBillDetailService.editQsFy(yjList);
        }
        List<OwnerLeaseBillDetail> lszc = ownerLeaseBillParam.getLszc();
        ownerLeaseBillDetailService.deleteByOwnerBillIdOnType(id,4);
        ownerLeaseBillDetailService.addGdfyByType(lszc,id,4);
        List<OwnerLeaseBillDetail> lssr = ownerLeaseBillParam.getLssr();
        ownerLeaseBillDetailService.deleteByOwnerBillIdOnType(id,5);
        ownerLeaseBillDetailService.addGdfyByType(lssr,id,5);
    }

    //撤銷到賬
    @Override
    public void editCxdz(OwnerLeaseBillParam ownerLeaseBillParam) {
        check(ownerLeaseBillParam);
        //檢測當前章黨是否是最新賬單
        OwnerLeaseBill ownerLeaseBill = this.queryOwnerLeaseBill(ownerLeaseBillParam);
        checkCxzd(ownerLeaseBill);
        Long ownerLeaseId = ownerLeaseBill.getOwnerLeaseId();
        //更新當前未到賬的賬單
        editNotDaoZangBill(ownerLeaseId);
        //更新賬單表
        Long id = ownerLeaseBill.getId();
        String updateSql="update owner_lease_bill set subtotal=0,receive_amount=null,receive_date=null,collection_type=null,bill_status=1,create_time=null,create_user=null where id =?";
        dbUtils.execSql(updateSql,id);
        //刪除賬單詳情
        ownerLeaseBillDetailService.deleteByOwnerBillId(id);
        //刪除流水賬單及其詳情
        billWaterService.deleteAllByType(id,"owner_lease_bill");
        //重新生成賬單詳情
        OwnerLease lease = ownerLeaseService.getByLeaseById(ownerLeaseId);
        //新增固定費用
        List<OwnerLeaseFees> ownerLeaseFees = ownerLeaseFeesService.getGdfyByLeaseId(ownerLeaseId);
        ownerLeaseBillDetailService.addGdfy(ownerLeaseFees,id);

        if (ownerLeaseBill.getQsNum().intValue()==1){
            //新增押金
            ownerLeaseBillDetailService.addYj(lease.getDeposit(),id,1);
        }
        //新增租金
        //基础设置
        BusBasicSettings one = busBasicSettingsService.getOne();
        //计算费用时月天数 （字典 0按固定30天算 1按月份实际天数
        int calculateStyle = one.getCalculateStyle();
        //账单金额取整 （字典 0关闭 1打开 小数点后四舍五入）
        int amount = one.getAmount();
        Integer receiptFu = lease.getReceiptFu();
        Integer receiptYj = lease.getReceiptYj();
        BigDecimal rent = ownerLeaseBill.getRent();
        Date rentStartDate = ownerLeaseBill.getRentStartDate();
        Date rentEndDate = ownerLeaseBill.getRentEndDate();
        BigDecimal rentMoney = CalculateQs.getRentMoney(amount, calculateStyle, receiptFu, receiptYj, rentStartDate, rentEndDate, rent);
        ownerLeaseBillDetailService.addZj(rentMoney,id);
    }

    /**
     * 撤銷到賬 更新當前未到賬的賬單為無效狀態 並刪除詳情
     * @param ownerLeaseId
     */
    private void editNotDaoZangBill(Long ownerLeaseId) {
        String sql="select * from owner_lease_bill where owner_lease_id =? and status=0 and bill_status=1 and qs_num<>1";
        OwnerLeaseBill first = dbUtils.getFirst(sql, OwnerLeaseBill.class, ownerLeaseId);
        if (null!=first){
            String updateSql="update owner_lease_bill set bill_status=5,create_time=null,create_user=null where id =?";
            dbUtils.execSql(updateSql,first.getId());
            //刪除賬單詳情
            ownerLeaseBillDetailService.deleteByOwnerBillId(first.getId());
        }
    }

    private void checkCxzd(OwnerLeaseBill ownerLeaseBill) {
        //當前賬單是否是已到賬狀態
        int intlue = ownerLeaseBill.getBillStatus().intValue();
        if (intlue!=2){
            throw new BusinessException(0,"當前賬單已不是到賬狀態！");
        }
        //是否是最新賬單
        String sql="select count(*) from owner_lease_bill where owner_lease_id =? and status=0 and bill_status=2 and qs_num>?";
        int intValue = dbUtils.getIntValue(sql, ownerLeaseBill.getOwnerLeaseId(),ownerLeaseBill.getQsNum());
        if (intValue>0){
            throw  new BusinessException(0,"當前賬單已不是最新的到賬賬單！");
        }
    }

    @Override
    public void editJz(OwnerLeaseBillParam ownerLeaseBillParam) {
        Long id = ownerLeaseBillParam.getId();
        check(ownerLeaseBillParam);
        OwnerLeaseBill ownerLeaseBill = this.queryOwnerLeaseBill(ownerLeaseBillParam);
        BigDecimal amountByBillId = ownerLeaseBillDetailService.getAmountByBillId(id);
        String receiveDate = ownerLeaseBillParam.getReceiveDate();
        ownerLeaseBill.setReceiveDate(DateUtil.parse(receiveDate,"yyyy-MM-dd"));
        ownerLeaseBill.setCollectionType(ownerLeaseBillParam.getCollectionType());
        ownerLeaseBill.setSubtotal(amountByBillId);
        ownerLeaseBill.setReceiveAmount(amountByBillId);
        int billStatus = ownerLeaseBill.getBillStatus();
        if (billStatus==1) {
            ownerLeaseBill.setBillStatus(2);
        }else {
            ownerLeaseBill.setBillStatus(4);
        }
        ownerLeaseBill.setCreateTime(new Date());
        ownerLeaseBill.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(ownerLeaseBill);
        //生成账单流水
        saveNextBillWater(ownerLeaseBill);
        //rentFree
        Long ownerLeaseId = ownerLeaseBill.getOwnerLeaseId();
        Integer qsNum = ownerLeaseBill.getQsNum();
        if (billStatus!=3) {
            String getNextBillSql="select * from owner_lease_bill where status=0 and bill_status =5  and owner_lease_id =? and qs_num=?";
            OwnerLeaseBill nextBill = dbUtils.getFirst(getNextBillSql, OwnerLeaseBill.class,ownerLeaseId, qsNum+1);
            if (null!=nextBill){
                saveNextBill(nextBill);
            }
        }
    }

    @Override
    public void editQsTz(OwnerLeaseBillParam ownerLeaseBillParam) {
        check(ownerLeaseBillParam);
        OwnerLeaseBill ownerLeaseBill = this.queryOwnerLeaseBill(ownerLeaseBillParam);
        Long id = ownerLeaseBill.getId();
        //更新賬單狀態
        String receiveDate = ownerLeaseBillParam.getReceiveDate();
        ownerLeaseBill.setReceiveDate(DateUtil.parse(receiveDate,"yyyy-MM-dd"));
        ownerLeaseBill.setCollectionType(ownerLeaseBillParam.getCollectionType());
        BigDecimal amountByBillId = ownerLeaseBillDetailService.getAmountByBillId(id);
        ownerLeaseBill.setSubtotal(amountByBillId);
        ownerLeaseBill.setReceiveAmount(amountByBillId);
        ownerLeaseBill.setBillStatus(4);
        ownerLeaseBill.setCreateTime(new Date());
        ownerLeaseBill.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(ownerLeaseBill);
        //生成账单流水
        saveNextBillWater(ownerLeaseBill);
        //修改租約狀態
        Long ownerLeaseId = ownerLeaseBill.getOwnerLeaseId();
        ownerLeaseService.editTuiZuQs(ownerLeaseId);
        //修改房間狀態---解除綁定關係
        busRoomService.editByOwnerJc(ownerLeaseId);
    }

    @Override
    public void editBillPlan(LeaseBillPlanResult ownerLeaseBillParam) {
        OwnerLeaseBillParam owneeaseBillParam=new OwnerLeaseBillParam();
        owneeaseBillParam.setId(ownerLeaseBillParam.getId());
        OwnerLeaseBill ownerLeaseBill = getById(owneeaseBillParam);
        BigDecimal rentPre = ownerLeaseBill.getRent();
        boolean rentFreeFlag = ownerLeaseBillParam.isRentFreeFlag();
        if (rentFreeFlag){
            ownerLeaseBill.setRentFree(1);
        }else {
            ownerLeaseBill.setRentFree(0);
        }
        boolean rentAdjustFlag = ownerLeaseBillParam.isRentAdjustFlag();
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        Date date = new Date();
        if (rentAdjustFlag){
            ownerLeaseBill.setRentAdjust(1);
            ownerLeaseBill.setRent(ownerLeaseBillParam.getRentWe());
            OwnerLeaseBillAdjust OwnerLeaseBillAdjust = ownerLeaseBillAdjustService.getByBillId(ownerLeaseBill.getId());
            if (null==OwnerLeaseBillAdjust){
                OwnerLeaseBillAdjust=new OwnerLeaseBillAdjust();
                OwnerLeaseBillAdjust.setCreateTime(date);
                OwnerLeaseBillAdjust.setCreateUser(sysLoginUserId);
                OwnerLeaseBillAdjust.setLeaseBillId(ownerLeaseBill.getId());
                OwnerLeaseBillAdjust.setAdjustStyle(ownerLeaseBillParam.getAdjustStyle());
                OwnerLeaseBillAdjust.setAdjustType(ownerLeaseBillParam.getAdjustType());
                OwnerLeaseBillAdjust.setChangeMoney(ownerLeaseBillParam.getChangeMoney());
                OwnerLeaseBillAdjust.setRent(ownerLeaseBillParam.getRentWe());
                ownerLeaseBillAdjustService.addEntity(OwnerLeaseBillAdjust);
            }else {
                OwnerLeaseBillAdjust.setUpdateTime(date);
                OwnerLeaseBillAdjust.setUpdateUser(sysLoginUserId);
                OwnerLeaseBillAdjust.setLeaseBillId(ownerLeaseBill.getId());
                OwnerLeaseBillAdjust.setAdjustStyle(ownerLeaseBillParam.getAdjustStyle());
                OwnerLeaseBillAdjust.setAdjustType(ownerLeaseBillParam.getAdjustType());
                OwnerLeaseBillAdjust.setChangeMoney(ownerLeaseBillParam.getChangeMoney());
                OwnerLeaseBillAdjust.setRent(ownerLeaseBillParam.getRentWe());
                dbUtils.update(OwnerLeaseBillAdjust);
            }
        }else {
            ownerLeaseBill.setRentAdjust(0);
        }
        ownerLeaseBill.setUpdateUser(sysLoginUserId);
        ownerLeaseBill.setUpdateTime(date);
        dbUtils.update(ownerLeaseBill);
        if(rentPre.compareTo(ownerLeaseBillParam.getRentWe()) != 0){
            if (rentAdjustFlag){
                BigDecimal decimal = makeMoney(ownerLeaseBillParam.getAdjustType(), ownerLeaseBillParam.getAdjustStyle(), ownerLeaseBillParam.getRent(), ownerLeaseBillParam.getChangeMoney());
                String update="update owner_lease_bill set rent = rent + ?,update_time=?,update_user=? where owner_lease_id=? and qs_num>? and bill_status=5";
                dbUtils.execSql(update,decimal,date,sysLoginUserId,ownerLeaseBill.getOwnerLeaseId(),ownerLeaseBill.getQsNum());
            }
        }
        if(rentPre.compareTo(ownerLeaseBillParam.getRentWe()) != 0||rentFreeFlag){
            int billStatus = ownerLeaseBill.getBillStatus();
            if (billStatus == 1){
                //重新生成租金
                ownerLeaseBillDetailService.deleteByOwnerBillIdOnType(ownerLeaseBill.getId(),1);
                BigDecimal en=new BigDecimal(0.00);
                if (!rentFreeFlag&&rentAdjustFlag){
                    //重新生成賬單詳情
                    OwnerLease lease = ownerLeaseService.getByLeaseById(ownerLeaseBill.getOwnerLeaseId());
                    //基础设置
                    BusBasicSettings one = busBasicSettingsService.getOne();
                    //计算费用时月天数 （字典 0按固定30天算 1按月份实际天数
                    int calculateStyle = one.getCalculateStyle();
                    //账单金额取整 （字典 0关闭 1打开 小数点后四舍五入）
                    int amount = one.getAmount();
                    //不免租金
                    BigDecimal rent = ownerLeaseBill.getRent();
                    Date rentStartDate = ownerLeaseBill.getRentStartDate();
                    Date rentEndDate = ownerLeaseBill.getRentEndDate();
                    Integer receiptFu = lease.getReceiptFu();
                    Integer receiptYj = lease.getReceiptYj();
                    en = CalculateQs.getRentMoney(amount, calculateStyle, receiptFu, receiptYj, rentStartDate, rentEndDate, rent);
                }
                ownerLeaseBillDetailService.addZj(en,ownerLeaseBill.getId());
            }
        }

    }
    private BigDecimal makeMoney(int adjustType, int adjustStyle, BigDecimal rent,BigDecimal changeMoney){
        BigDecimal rentPrice = new BigDecimal(0.00);
        if (adjustType == 1) {
            if (adjustStyle == 1) {
                rentPrice = changeMoney;
            } else {
                rentPrice = DecimalUtils.multiply(rent,DecimalUtils.divide(changeMoney,new BigDecimal(100)));
            }
        } else {
            if (adjustStyle == 1) {
                rentPrice = changeMoney.negate();
            } else {
                rentPrice = DecimalUtils.multiply(rent,DecimalUtils.divide(changeMoney,new BigDecimal(100))).negate();
            }
        }
        return rentPrice;
    }
    private void saveNextBillWater(OwnerLeaseBill ownerLeaseBill) {
        // 保存流水詳情表
        OwnerLease byLeaseById = ownerLeaseService.getByLeaseById(ownerLeaseBill.getOwnerLeaseId());
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        Date date = new Date();
        BillWater billWaterParam = getBillWaterParam(ownerLeaseBill,byLeaseById,sysLoginUserId);
        Long billWaterKey = billWaterService.add(billWaterParam);
        //保存流水房間關聯表
        List<OwnerLeaseRoom> roomNamesByOwnerId = ownerLeaseRoomService.getRoomNamesByOwnerId(byLeaseById.getId());
        BillWaterRoom billWaterRoom=null;
        OwnerLeaseRoom ownerLeaseRoom =null;
        String name = byLeaseById.getName();
        for (int i = 0; i < roomNamesByOwnerId.size(); i++) {
            ownerLeaseRoom = roomNamesByOwnerId.get(i);
            billWaterRoom=new BillWaterRoom();
            billWaterRoom.setBillWaterId(billWaterKey);
            billWaterRoom.setRoomId(ownerLeaseRoom.getRoomId());
            billWaterRoom.setRoomName(ownerLeaseRoom.getRoomName());
            billWaterRoom.setName(name);
            dbUtils.insert(billWaterRoom);
        }

        List<OwnerLeaseBillDetail> billDetail = ownerLeaseBillDetailService.getListByBillIdForRead(ownerLeaseBill.getId());
        BillWaterDetail billWaterDetail=null;
        for (int i = 0; i < billDetail.size(); i++) {
            OwnerLeaseBillDetail houseBillDetailResult = billDetail.get(i);
            billWaterDetail=new BillWaterDetail();
            billWaterDetail.setBillInOutType(houseBillDetailResult.getBillInOutType());
            billWaterDetail.setAmount(DecimalUtils.toBigDecimal(houseBillDetailResult.getAmount()));
            billWaterDetail.setBillWaterId(billWaterKey);
            billWaterDetail.setName(houseBillDetailResult.getRentAmountName());
            billWaterDetail.setStatus(0);
            billWaterDetail.setCreateUser(sysLoginUserId);
            billWaterDetail.setCreateTime(date);
            billWaterDetailService.add(billWaterDetail);
        }
    }

    private BillWater getBillWaterParam(OwnerLeaseBill ownerLeaseBill, OwnerLease ownerLease, Long sysLoginUserId ) {
        BillWater billWaterParam =new BillWater();
        billWaterParam.setRoomName(ownerLease.getRoomName());
        billWaterParam.setName(ownerLease.getName());
        //業主訂單
        billWaterParam.setSource(7);
        billWaterParam.setAmount(ownerLeaseBill.getReceiveAmount());
        billWaterParam.setReceiveDate(ownerLeaseBill.getReceiveDate());
        billWaterParam.setShouldReceiveDate(ownerLeaseBill.getRentedDay());
        Date date = new Date();
        billWaterParam.setOperatingDate(date);
        billWaterParam.setTransaction(ownerLeaseBill.getCollectionType());
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        billWaterParam.setManagerId(sysLoginUserId);
        billWaterParam.setManager(sysLoginUser.getName());
        billWaterParam.setManagertTime(date);
        billWaterParam.setAuditFlag(0);
        billWaterParam.setNo(ownerLeaseBill.getNo());
        billWaterParam.setBillInOutType(2);
        billWaterParam.setBillId(ownerLeaseBill.getId());
        billWaterParam.setBillTable("owner_lease_bill");
        billWaterParam.setStatus(0);
        billWaterParam.setCreateUser(sysLoginUserId);
        billWaterParam.setCreateTime(date);
        return billWaterParam;
    }

    private void saveNextBill(OwnerLeaseBill nextBill) {
        Long billId = nextBill.getId();
        Long ownerLeaseId = nextBill.getOwnerLeaseId();
        //是否免租金
        int rentFree = nextBill.getRentFree();
        if (rentFree==0){
            //重新生成賬單詳情
            OwnerLease lease = ownerLeaseService.getByLeaseById(ownerLeaseId);
            //基础设置
            BusBasicSettings one = busBasicSettingsService.getOne();
            //计算费用时月天数 （字典 0按固定30天算 1按月份实际天数
            int calculateStyle = one.getCalculateStyle();
            //账单金额取整 （字典 0关闭 1打开 小数点后四舍五入）
            int amount = one.getAmount();
            //不免租金
            BigDecimal rent = nextBill.getRent();
            Date rentStartDate = nextBill.getRentStartDate();
            Date rentEndDate = nextBill.getRentEndDate();
            Integer receiptFu = lease.getReceiptFu();
            Integer receiptYj = lease.getReceiptYj();
            BigDecimal rentMoney = CalculateQs.getRentMoney(amount, calculateStyle, receiptFu, receiptYj, rentStartDate, rentEndDate, rent);
            ownerLeaseBillDetailService.addZj(rentMoney,billId);
        }
        nextBill.setBillStatus(1);
        nextBill.setCreateTime(new Date());
        nextBill.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(nextBill);
        List<OwnerLeaseFees> ownerLeaseFees = ownerLeaseFeesService.getGdfyByLeaseId(ownerLeaseId);
        //新增固定費用
        ownerLeaseBillDetailService.addGdfy(ownerLeaseFees,billId);
    }

    private void check(OwnerLeaseBillParam ownerLeaseBillParam) {
        String sql="select count(*) from owner_lease where status=0 and lease_status=2 and id =?";
        int intValue = dbUtils.getIntValue(sql, ownerLeaseBillParam.getOwnerLeaseId());
        if (intValue>0){
            throw new BusinessException(0,"業主已退租！");
        }
        String sqlBill="select count(*) from owner_lease_bill where status=0 and ( bill_status=2 or  bill_status=4) and id =?";
        int intValueBill = dbUtils.getIntValue(sqlBill, ownerLeaseBillParam.getId());
        if (intValueBill>0){
            throw new BusinessException(0,"該賬單已到賬！");
        }
    }
    @Override
    public OwnerLeaseBill detail(OwnerLeaseBillParam ownerLeaseBillParam) {
        return this.queryOwnerLeaseBill(ownerLeaseBillParam);
    }

    @Override
    public LeaseBillPlanResult detailByBillId(OwnerLeaseBillParam ownerLeaseBillParam) {
        String sql="select a.*,IFNULL(b.adjust_style,1) as adjust_style,IFNULL(b.adjust_type,1) as adjust_type,IFNULL(b.change_money,0) as change_money,b.rent as rentwe from owner_lease_bill a LEFT JOIN owner_lease_bill_adjust b on a.id=b.lease_bill_id where a.id =? ";
        LeaseBillPlanResult ownerLeaseBillPlanResult = dbUtils.get(sql, LeaseBillPlanResult.class, ownerLeaseBillParam.getId());
        ownerLeaseBillPlanResult.setZq(ownerLeaseBillPlanResult.getRentStartDate()+"-"+ownerLeaseBillPlanResult.getRentEndDate());
        int rentAdjust = ownerLeaseBillPlanResult.getRentAdjust();
        if (rentAdjust ==1){
            ownerLeaseBillPlanResult.setRentAdjustFlag(true);
        }else {
            ownerLeaseBillPlanResult.setRentAdjustFlag(false);
        }
        int rentFree = ownerLeaseBillPlanResult.getRentFree();
        if (rentFree ==1){
            ownerLeaseBillPlanResult.setRentFreeFlag(true);
        }else {
            ownerLeaseBillPlanResult.setRentFreeFlag(false);
        }
        if (ownerLeaseBillPlanResult.getAdjustType() == null) {
            ownerLeaseBillPlanResult.setAdjustType(1);
        }
        if (ownerLeaseBillPlanResult.getAdjustStyle() == null) {
            ownerLeaseBillPlanResult.setAdjustStyle(1);
        }
        if (ownerLeaseBillPlanResult.getRentWe() == null) {
            ownerLeaseBillPlanResult.setRentWe(ownerLeaseBillPlanResult.getRent());
        }
        return ownerLeaseBillPlanResult;
    }

    @Override
    public OwnerBillDetaillReadResult getOwnerBillDetailReadOnly(Long billId) {
        String sql="select * from owner_lease_bill where id =? ";
        OwnerBillDetaillReadResult first = dbUtils.getFirst(sql, OwnerBillDetaillReadResult.class, billId);
        OwnerLease byLease = ownerLeaseService.getByLeaseById(first.getOwnerLeaseId());
        first.setName(byLease.getName());
        first.setPhone(byLease.getPhone());
        first.setMainRent(byLease.getRent());
        first.setReceiptCycle(byLease.getReceiptCycle());
        first.setLeaseStatus(byLease.getLeaseStatus());
        List<OwnerLeaseBillDetail> listByLeaseIdForRead = ownerLeaseBillDetailService.getListByBillIdForRead(billId);
        BigDecimal total=new BigDecimal(0.00);
        for (int i1 = 0; i1 < listByLeaseIdForRead.size(); i1++) {
            OwnerLeaseBillDetail ownerLeaseBillDetail = listByLeaseIdForRead.get(i1);
            if (ownerLeaseBillDetail.getBillInOutType().intValue()==2){
                ownerLeaseBillDetail.setAmount(ownerLeaseBillDetail.getAmount().negate());
                total=DecimalUtils.add(total,ownerLeaseBillDetail.getAmount());
            }
        }
        first.setSubtotal(DecimalUtils.toPlainString(total));
        first.setDetails(listByLeaseIdForRead);
        List<OwnerLeaseRoom> roomNames = ownerLeaseRoomService.getRoomNamesByOwnerId(first.getOwnerLeaseId());
        first.setRoomNames(roomNames);
        if (first.getBillStatus().intValue()==2||first.getBillStatus().intValue()==4){
            BusMeansOfTransaction oneById = busMeansOfTransactionService.getOneById(first.getCollectionType());
            if (null!=oneById){
                first.setCollectionTypeName(oneById.getName());
            }

        }
        return first;
    }

    @Override
    public OwnerBillDetaillEditResult getOwnerBillDetailForEdit(Long billId) {
        String sql="select * from owner_lease_bill where id =? ";
        OwnerBillDetaillEditResult first = dbUtils.getFirst(sql, OwnerBillDetaillEditResult.class, billId);
        OwnerLease byLease = ownerLeaseService.getByLeaseById(first.getOwnerLeaseId());
        first.setName(byLease.getName());
        first.setPhone(byLease.getPhone());
        // 1 不修改   2臨時支出 3 臨時收入
        List<OwnerLeaseBillDetail> listByBillIdForEditByType = ownerLeaseBillDetailService.getListByBillIdForEditByType(billId, 1);
        first.setNoEditdetails(listByBillIdForEditByType);
        List<OwnerLeaseBillDetail> lszc = ownerLeaseBillDetailService.getListByBillIdForEditByType(billId, 2);
        first.setLszc(lszc);
        List<OwnerLeaseBillDetail> lssr = ownerLeaseBillDetailService.getListByBillIdForEditByType(billId, 3);
        first.setLssr(lssr);
        return first;
    }

    @Override
    public List<OwnerLeaseBillPlanResult> getBillListByLeaseId(Long leaseId) {
        OwnerLease byLeaseById = ownerLeaseService.getByLeaseById(leaseId);
        int receiptYj = byLeaseById.getReceiptYj();
        String sql="select a.*,IFNULL(b.adjust_type,0) as adjust_type,b.adjust_style,b.change_money from owner_lease_bill a LEFT JOIN owner_lease_bill_adjust b on a.id=b.lease_bill_id where a.owner_lease_id =? and a.status=0 and a.bill_status not in (3,4) group by a.qs_num asc";
        List<OwnerLeaseBillPlanResult> query = dbUtils.query(sql, OwnerLeaseBillPlanResult.class, leaseId);
        query.forEach(item->{
            DayCompare timeLength = CalculateQs.getTimeLength(item.getRentStartDate(), item.getRentEndDate(), receiptYj);
            String sc="";
            if (receiptYj==1){
                sc=timeLength.getDay()+"日";
            }else if (receiptYj==2){
                sc=timeLength.getMonth()+"月"+timeLength.getDay()+"日";
            }else if (receiptYj==3){
                sc=timeLength.getYear()+"年"+timeLength.getMonth()+"月"+timeLength.getDay()+"日";
            }
            item.setSc(sc);
            int billStatus = item.getBillStatus();
            if (billStatus ==2){
                item.setEditFlag(0);
            }
            int qsNum = item.getQsNum();
            if (qsNum ==1){
                item.setEditFlag(0);
            }
            int adjustType = item.getAdjustType();
            String zRemark="";
            if (adjustType!=0){
                int adjustStyle = item.getAdjustStyle();
                String dw="元/年";
                if (adjustStyle==2){
                    dw="%";
                }
                String dwt="涨";
                if (adjustType==2){
                    dwt="降";
                }
                BigDecimal changeMoney = item.getChangeMoney();
                zRemark = dwt+changeMoney+dw;
            }
            item.setZremark(zRemark);
        });
        return query;
    }

    /**
     * 获取業主賬單
     *
     * @author anti
     * @date 2021-05-20 14:25:38
     */
    private OwnerLeaseBill queryOwnerLeaseBill(OwnerLeaseBillParam ownerLeaseBillParam) {
        OwnerLeaseBill ownerLeaseBill = this.getById(ownerLeaseBillParam);
        if (ObjectUtil.isNull(ownerLeaseBill)) {
            throw new BusinessException(OwnerLeaseBillExceptionEnum.NOT_EXIST);
        }
        return ownerLeaseBill;
    }
}
